<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 参与活动
 *
 * @icon fa fa-circle-o
 */
class ActivityTake extends Backend
{

    /**
     * ActivityTake模型对象
     * @var \app\admin\model\ActivityTake
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ActivityTake;
        $this->view->assign("activeTypsList", $this->model->getActiveTypsList());
        $this->view->assign("isStandsList", $this->model->getIsStandsList());
        $this->view->assign("processList", $this->model->getProcessList());
        $this->view->assign("isAllotList", $this->model->getIsAllotList());
        $this->view->assign("isDueList", $this->model->getIsDueList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->alias('a')
            ->join("(select id ids,concat(nickname,'(',insert(mobile,4,4,'****'),')') nick from fd_user ) b", "a.uid=b.ids", "left")
            ->join("(select id ids,username from fd_admin ) c", "a.process_id=c.ids", "left")
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as $vals) {
            $vals->start = date("Y-m-d", $vals->start);
            $vals->ends = date("Y-m-d", $vals->ends);
            $vals->nickname = $vals->process_uid ? Db::name("user")->where("admin_id", $vals->process_uid)->value('nickname') : "无";
            $vals->alloct = $vals->allot_uid ? Db::name("user")->where("admin_id", $vals->allot_uid)->value('nickname') : "无";
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 确认处理
     */
    public function confirm($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->is_stands == 2) {
            $this->error(__('未达标，禁止处理操作'));
        }
        if ($row->process == 1) {
            $this->error(__('已处理，无需重复操作'));
        }
        if ($row->process == 3) {
            $this->error(__('订单无效已拒绝，无需重复操作'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign("processList", [3 => "拒绝", 1 => "同意"]);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $params["process_id"] = $this->auth->id;
            $uid = Db::name("user")->where("admin_id", $params["process_id"])->value('id');
            $params["process_uid"] =  $uid ? $uid : 0;
            $params["process_time"] = time();
            $row->allowField(true)->save($params);
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
